#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
main()
{
	int pipe_fd[2];
	pid_t pid;
	char r_buf[100];
	char w_buf[4];
	char* p_wbuf;
	int r_num;
	int cmd;
	
	memset(r_buf,0,sizeof(r_buf));
	memset(w_buf,0,sizeof(r_buf));
	p_wbuf=w_buf;
	if(pipe(pipe_fd)<0)
	{
		printf("pipe create error\n");
		return -1;
	}
	
	if((pid=fork())==0)
	{
		printf("child: start\n");
		close(pipe_fd[1]);
		sleep(1);//确保父进程关闭写端
		while(1){
			printf("child: start reading\n");
			r_num=read(pipe_fd[0],r_buf,100);
			if(r_num == 0) {
				printf(	"child: read err, ret 0\n");
				break;
			}
			printf(	"child: read over, len is %d, data is: %s\n",r_num,r_buf);
		}
		close(pipe_fd[0]);
		printf("child: close fd[1] over\n");
		exit(0);
	}
	else if(pid>0)
	{
		printf("parent: start\n");
		strcpy(w_buf,"123");
		close(pipe_fd[0]);//read
		sleep(3);//确保父进程关闭写端
		printf("parent: start writing '%s'\n", w_buf);
		if(write(pipe_fd[1],w_buf,4)!=-1)
		printf("parent: write over\n");
		sleep(3);//确保父进程关闭写端
		printf("parent: start writing '%s'\n", w_buf);
		if(write(pipe_fd[1],w_buf,4)!=-1)
		printf("parent: write over\n");
		sleep(1);
		close(pipe_fd[1]);//write
		printf("parent: close fd[1] over\n");
	}	
}
